package com.shangxian.giveithome.service.impl;

import com.shangxian.giveithome.code.AuthCode;
import com.shangxian.giveithome.code.CommonCode;
import com.shangxian.giveithome.code.UserCode;
import com.shangxian.giveithome.entity.PageableDetails;
import com.shangxian.giveithome.entity.community.IssueImg;
import com.shangxian.giveithome.entity.report.BlackList;
import com.shangxian.giveithome.entity.report.Forbidden;
import com.shangxian.giveithome.entity.report.InputBlackList.Number;
import com.shangxian.giveithome.entity.report.InputBlackList.ReportList;
import com.shangxian.giveithome.entity.report.InputBlackList.UserConditionParam;
import com.shangxian.giveithome.entity.report.outputParams.ResultBlackList;
import com.shangxian.giveithome.entity.report.outputParams.ResultList;
import com.shangxian.giveithome.entity.report.outputParams.ResultUser;
import com.shangxian.giveithome.exception.ExceptionUtils;
import com.shangxian.giveithome.mapper.IssueImgMapper;
import com.shangxian.giveithome.mapper.NewReportMapper;
import com.shangxian.giveithome.service.NewReportService;
import com.shangxian.giveithome.utils.PageUtils;
import com.shangxian.giveithome.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * 新举报中心业务层
 */
@Service
public class NewReportServiceImpl implements NewReportService {

    @Resource
    private NewReportMapper newReportMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Resource
    private HttpServletRequest request;

    @Resource
    private IssueImgMapper issueImgMapper;

    @Override
    public PageableDetails findBlackListByUserOrPhone(String value, Pageable pageable) {
        if ("null".equals(value)){
            ExceptionUtils.error(CommonCode.DATA_ERROR);
        }
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        int total = newReportMapper.findBlackListByUserOrPhoneTotal(value);
        if (total == 0){
            return new PageableDetails(pageNumber,pageSize,total,returnPages(total,pageSize),new ArrayList<>());
        }
        List<ResultList> resultLists = newReportMapper.findBlackListByUserOrPhone(value,pageNumber*pageSize,pageSize);
        return new PageableDetails(pageNumber,pageSize,total,returnPages(total,pageSize),resultLists);
    }

    @Override
    public void submitReport(ReportList reportList) {
        BlackList blackList = new BlackList();
        blackList.setType(reportList.getType());
        blackList.setReportContent(reportList.getReportContent());
        blackList.setName(reportList.getName());
        blackList.setPhone(reportList.getPhone());
        blackList.setWechat(reportList.getWechat());
        blackList.setImgId(reportList.getImgId());
        blackList.setOtherContent(reportList.getOtherContent());
        blackList.setReportTime(new Date());
        blackList.setUserId(redisUtils.getHeader(request).getId());
        int count = newReportMapper.submitReport(blackList);
        if (count <1){
            ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
    }

    @Override
    public PageableDetails findBlackListHistory(Long state, Pageable pageable) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        int total = newReportMapper.findBlackListHistoryTotal(state);
        if (total == 0){
            return new PageableDetails(pageNumber,pageSize,total,returnPages(total,pageSize),new ArrayList<>());
        }
        List<ResultBlackList> resultBlackLists = newReportMapper.findBlackListHistory(state,pageNumber*pageSize,pageSize);
        List<Long> imgIds = resultBlackLists.stream().map(ResultBlackList::getImgId).collect(Collectors.toList());
        if (imgIds.size()<1){
            return new PageableDetails(pageNumber,pageSize,total,returnPages(total,pageSize),resultBlackLists);
        }
        List<IssueImg> issueImgs = issueImgMapper.findAllIssueImgByIds(imgIds);
        resultBlackLists.forEach(resultBlackList -> {
            List<IssueImg> imgList = new ArrayList<>();
            for (IssueImg issueImg : issueImgs) {
                if (issueImg.getKeyId() != null && resultBlackList.getImgId() != null && issueImg.getKeyId().equals(resultBlackList.getImgId())){
                    imgList.add(issueImg);
                }
                resultBlackList.setImgs(imgList);
            }
        });
        return new PageableDetails(pageNumber,pageSize,total,returnPages(total,pageSize),resultBlackLists);
    }

    @Override
    public PageableDetails findAllBlockedUser(Pageable pageable) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        int total = newReportMapper.findAllBlockedUserTotal();
        if (total == 0){
            return new PageableDetails(pageNumber,pageSize,total,returnPages(total,pageSize),new ArrayList<>());
        }
        List<Forbidden> forbiddenList = newReportMapper.findAllBlockedUser(pageNumber*pageSize,pageSize);
        return new PageableDetails(pageNumber,pageSize,total,returnPages(total,pageSize),forbiddenList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void blockedUser(Number numberParam) {
        System.out.println(numberParam);
        //不需要校验手机号了
//        if (numberParam.getPhone() == null) {
//            ExceptionUtils.error(AuthCode.PHONE_ERROR);
//        }
        int count1 = newReportMapper.IsBlock(numberParam.getPhone());
        if (numberParam.getId() != null) {
            int count = newReportMapper.dealBlockedReport(numberParam.getId());
            if (count < 1) {
                ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
            }
            //判断是否已经被禁用
            if (count1 >0){
                return;
            }
        }
        //判断是否被封禁过
        int count2 = newReportMapper.IsExistForbidden(numberParam.getPhone());
        if (count2 >0){
            int count = newReportMapper.UBlockUser(numberParam);
            int count3 = newReportMapper.UdealBlockedReport(numberParam.getPhone());
            if (count <0){
                ExceptionUtils.error(UserCode.USER_AUDIT_FAIL);
            }
            return;
        }
            Forbidden forbidden = new Forbidden();
            forbidden.setCreateTime(new Date());
            forbidden.setPhone(numberParam.getPhone());
            forbidden.setName(numberParam.getName());
            forbidden.setWechat(numberParam.getWechat());
        System.out.println(forbidden);
            int count3 = newReportMapper.blockedUser(forbidden);
            if (count3 < 1) {
                ExceptionUtils.error(UserCode.USER_AUDIT_FAIL);
            }
    }

    @Override
    public void unblockUser(Number param) {
        if (param.getPhone() == null ){
            int count = newReportMapper.NdealBlackUser(param.getId());
            if (count <1){
                ExceptionUtils.error(UserCode.USER_UNBLOCK_FAIL);
            }
            return;
        }
        int count = newReportMapper.IsBlock(param.getPhone());
        if (count <1){
            ExceptionUtils.error(UserCode.USER_NULL_AUDIT);
        }
        int count2 = newReportMapper.dealUnblockUser(param.getPhone());
        int count3 = newReportMapper.dealBlackUnblockUser(param.getPhone());
        if (count2<0 && count3 <0){
            ExceptionUtils.error(UserCode.USER_UNBLOCK_FAIL);
        }
    }

    @Override
    public void auditNormal(Number numberParam) {
        if (numberParam.getPhone() == null){
            ExceptionUtils.error(AuthCode.PHONE_ERROR);
        }
        int count = newReportMapper.auditNormal(numberParam.getId(),numberParam.getPhone());
        if (count <1){
            ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
    }

    @Override
    public PageableDetails findAllUser(UserConditionParam condition, Pageable pageable) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        int total = newReportMapper.findAllUserTotalByCondition(condition);
        if (total == 0){
            return new PageableDetails(pageNumber,pageSize,total,returnPages(total,pageSize),new ArrayList<>());
        }
        List<ResultUser> userList = newReportMapper.findAllUser(condition,pageNumber*pageSize,pageSize);
        return new PageableDetails(pageNumber,pageSize,total,returnPages(total,pageSize),userList);
    }


    /**
     * 返回
     *
     * @param pageNumber 当前页
     * @param pageSize   每页条数
     * @param count      总条数
     * @param list       返回数据
     * @param <T>        泛型
     * @return
     */
    public <T> PageableDetails returnPageable(int pageNumber, Integer pageSize, Integer count, List<T> list) {
        return new PageableDetails<>(pageNumber, pageSize, count, list);
    }


    /**
     * 返回总页数
     *
     * @param total
     * @param pageSize
     * @return
     */
    public int returnPages(int total, int pageSize) {
        return PageUtils.returnPages(total, pageSize);
    }

}
